home *** CD-ROM | disk | FTP | other *** search
/ Software Vault: The Gold Collection / Software Vault - The Gold Collection (American Databankers) (1993).ISO / cdr49 / pgp23src.zip / ARMOR.C < prev    next >
C/C++ Source or Header  |  1993-06-11  |  26KB  |  976 lines

  1. /*    armor.c  - ASCII/binary encoding/decoding based partly on PEM RFC1113.
  2.     PGP: Pretty Good(tm) Privacy - public key cryptography for the masses.
  3.  
  4.     (c) Copyright 1990-1992 by Philip Zimmermann.  All rights reserved.
  5.     The author assumes no liability for damages resulting from the use
  6.     of this software, even if the damage results from defects in this
  7.     software.  No warranty is expressed or implied.
  8.  
  9.     All the source code Philip Zimmermann wrote for PGP is available for
  10.     free under the "Copyleft" General Public License from the Free
  11.     Software Foundation.  A copy of that license agreement is included in
  12.     the source release package of PGP.  Code developed by others for PGP
  13.     is also freely available.  Other code that has been incorporated into
  14.     PGP from other sources was either originally published in the public
  15.     domain or was used with permission from the various authors.  See the
  16.     PGP User's Guide for more complete information about licensing,
  17.     patent restrictions on certain algorithms, trademarks, copyrights,
  18.     and export controls.  
  19. */
  20.  
  21. #include <ctype.h>
  22. #include <stdio.h>
  23. #include <string.h>
  24. #include "mpilib.h"
  25. #include "fileio.h"
  26. #include "mpiio.h"
  27. #include "language.h"
  28. #include "pgp.h"
  29. #include "crypto.h"
  30. #include "armor.h"
  31.  
  32. static int dpem_file(char *infile, char *outfile);
  33. static crcword crchware(byte ch, crcword poly, crcword accum);
  34. static int pem_file(char *infilename, char *outfilename, char *clearfilename);
  35. static int pemdecode(FILE *in, FILE *out);
  36. static void mk_crctbl(crcword poly);
  37. static boolean is_pemfile(char *infile);
  38.  
  39. /*     Begin PEM routines.
  40.     This converts a binary file into printable ASCII characters, in a
  41.     radix-64 form mostly compatible with the PEM RFC1113 format.
  42.     This makes it easier to send encrypted files over a 7-bit channel.
  43. */
  44.  
  45. /* Index this array by a 6 bit value to get the character corresponding
  46.  * to that value.
  47.  */
  48. static
  49. unsigned char bintoasc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\
  50. abcdefghijklmnopqrstuvwxyz0123456789+/";
  51.  
  52. /* Index this array by a 7 bit value to get the 6-bit binary field
  53.  * corresponding to that value.  Any illegal characters return high bit set.
  54.  */
  55. static
  56. unsigned char asctobin[] = {
  57.     0200,0200,0200,0200,0200,0200,0200,0200,
  58.     0200,0200,0200,0200,0200,0200,0200,0200,
  59.     0200,0200,0200,0200,0200,0200,0200,0200,
  60.     0200,0200,0200,0200,0200,0200,0200,0200,
  61.     0200,0200,0200,0200,0200,0200,0200,0200,
  62.     0200,0200,0200,0076,0200,0200,0200,0077,
  63.     0064,0065,0066,0067,0070,0071,0072,0073,
  64.     0074,0075,0200,0200,0200,0200,0200,0200,
  65.     0200,0000,0001,0002,0003,0004,0005,0006,
  66.     0007,0010,0011,0012,0013,0014,0015,0016,
  67.     0017,0020,0021,0022,0023,0024,0025,0026,
  68.     0027,0030,0031,0200,0200,0200,0200,0200,
  69.     0200,0032,0033,0034,0035,0036,0037,0040,
  70.     0041,0042,0043,0044,0045,0046,0047,0050,
  71.     0051,0052,0053,0054,0055,0056,0057,0060,
  72.     0061,0062,0063,0200,0200,0200,0200,0200
  73. };
  74. static long    infile_line;        /* Current line number for mult decodes */
  75.  
  76. /************************************************************************/
  77.  
  78. /* CRC Routines. */
  79. /*    These CRC functions are derived from code in chapter 19 of the book 
  80.     "C Programmer's Guide to Serial Communications", by Joe Campbell.
  81.     Generalized to any CRC width by Philip Zimmermann.
  82. */
  83.  
  84. #define byte unsigned char
  85.  
  86. #define CRCBITS 24    /* may be 16, 24, or 32 */
  87. /* #define maskcrc(crc) ((crcword)(crc)) */    /* if CRCBITS is 16 or 32 */
  88. #define maskcrc(crc) ((crc) & 0xffffffL)    /* if CRCBITS is 24 */
  89. #define CRCHIBIT ((crcword) (1L<<(CRCBITS-1))) /* 0x8000 if CRCBITS is 16 */
  90. #define CRCSHIFTS (CRCBITS-8)
  91.  
  92. /*    Notes on making a good 24-bit CRC--
  93.     The primitive irreducible polynomial of degree 23 over GF(2),
  94.     040435651 (octal), comes from Appendix C of "Error Correcting Codes,
  95.     2nd edition" by Peterson and Weldon, page 490.  This polynomial was
  96.     chosen for its uniform density of ones and zeros, which has better
  97.     error detection properties than polynomials with a minimal number of
  98.     nonzero terms.  Multiplying this primitive degree-23 polynomial by
  99.     the polynomial x+1 yields the additional property of detecting any
  100.     odd number of bits in error, which means it adds parity.  This 
  101.     approach was recommended by Neal Glover.
  102.  
  103.     To multiply the polynomial 040435651 by x+1, shift it left 1 bit and
  104.     bitwise add (xor) the unshifted version back in.  Dropping the unused 
  105.     upper bit (bit 24) produces a CRC-24 generator bitmask of 041446373 
  106.     octal, or 0x864cfb hex.  
  107.  
  108.     You can detect spurious leading zeros or framing errors in the 
  109.     message by initializing the CRC accumulator to some agreed-upon 
  110.     nonzero "random-like" value, but this is a bit nonstandard.  
  111. */
  112.  
  113. #define CCITTCRC 0x1021 /* CCITT's 16-bit CRC generator polynomial */
  114. #define PRZCRC 0x864cfbL /* PRZ's 24-bit CRC generator polynomial */
  115. #define CRCINIT 0xB704CEL    /* Init value for CRC accumulator */
  116.  
  117. static
  118. crcword crctable[256];        /* Table for speeding up CRC's */
  119.  
  120. /*    mk_crctbl derives a CRC lookup table from the CRC polynomial.
  121.     The table is used later by crcupdate function given below.
  122.     mk_crctbl only needs to be called once at the dawn of time.
  123.  
  124.     The theory behind mk_crctbl is that table[i] is initialized
  125.     with the CRC of i, and this is related to the CRC of i>>1,
  126.     so the CRC of i>>1 (pointed to by p) can be used to derive
  127.     the CRC of i (pointed to by q).
  128. */
  129. static
  130. void mk_crctbl(crcword poly)
  131. {    int i;
  132.     crcword t, *p, *q;
  133.     p = q = crctable;
  134.     *q++ = 0;
  135.     *q++ = poly;
  136.     for (i = 1; i < 128; i++)
  137.     {    t = *++p;
  138.         if (t & CRCHIBIT)
  139.         {    t <<= 1;
  140.             *q++ = t ^ poly;
  141.             *q++ = t;
  142.         }
  143.         else
  144.         {    t <<= 1;
  145.             *q++ = t;
  146.             *q++ = t ^ poly;
  147.         }
  148.     }
  149. }
  150.  
  151.  
  152. /*    crcupdate calculates a CRC using the fast table-lookup method.
  153.     Returns new updated CRC accumulator.
  154. */
  155. crcword crcupdate(byte data, register crcword accum)
  156. {    byte combined_value;
  157.  
  158.     /* XOR the MSByte of the accum with the data byte */
  159.     combined_value = (accum >> CRCSHIFTS) ^ data;
  160.     accum = (accum << 8) ^ crctable[combined_value];
  161.     return (maskcrc(accum));
  162. }    /* crcupdate */
  163.  
  164. /* Initialize the CRC table using our codes */
  165. void init_crc(void)
  166. {    mk_crctbl(PRZCRC);
  167. }
  168.  
  169.  
  170. /************************************************************************/
  171.  
  172.  
  173. /* ENC is the basic 1 character encoding function to make a char printing */
  174. #define ENC(c) ((int)bintoasc[((c) & 077)])
  175. #define PAD        '='
  176.  
  177. /*
  178.  * output one group of up to 3 bytes, pointed at by p, on file f.
  179.  * if fewer than 3 are present, the 1 or two extras must be zeros.
  180.  */
  181. static void outdec(char *p, FILE *f, int count)
  182. {
  183.     int c1, c2, c3, c4;
  184.  
  185.     c1 = *p >> 2;
  186.     c2 = ((*p << 4) & 060) | ((p[1] >> 4) & 017);
  187.     c3 = ((p[1] << 2) & 074) | ((p[2] >> 6) & 03);
  188.     c4 = p[2] & 077;
  189.     putc(ENC(c1), f);
  190.     putc(ENC(c2), f);
  191.     if (count == 1)
  192.     {    putc(PAD, f);
  193.         putc(PAD, f);
  194.     }
  195.     else
  196.     {    putc(ENC(c3), f);
  197.         if (count == 2)
  198.             putc(PAD, f);
  199.         else
  200.             putc(ENC(c4), f);
  201.     }
  202. }    /* outdec */
  203.  
  204.  
  205. /* Output the CRC value, MSB first per normal CRC conventions */
  206. static void outcrc (word32 crc, FILE *outFile)
  207. {    /* Output crc */
  208.     char crcbuf[4];
  209.     crcbuf[0] = (crc>>16) & 0xff;
  210.     crcbuf[1] = (crc>>8) & 0xff;
  211.     crcbuf[2] = (crc>>0) & 0xff;
  212.     putc(PAD,outFile);
  213.     outdec (crcbuf,outFile,3);
  214.     putc('\n',outFile);
  215. }    /* outcrc */
  216.  
  217. /* Return filename for output (text mode), but replace last letter of
  218.  * filename with the ascii for num (last two letters if num > 10).
  219.  */
  220. static char *numFilename( char *fname, int num)
  221. {    static char    fnamenum[MAX_PATH];
  222.     int        len;
  223.  
  224.     strcpy (fnamenum, fname);
  225.     len = strlen (fnamenum);
  226.     if (num < 10)
  227.         fnamenum[len-1] = '0' + num;
  228.     else    /* If num > 100, this will be slightly screwy */
  229.     {    fnamenum[len-2] = '0' + (num / 10);
  230.         fnamenum[len-1] = '0' + (num % 10);
  231.     }
  232.     return(fnamenum);
  233. }
  234.  
  235. /*
  236.  * Read a line from file f, buf must be able to hold at least 80 characters.
  237.  * Strips trailing spaces, can read LF, CRLF and CR textfiles.
  238.  */
  239. static char *
  240. get_armor_line(char *buf, FILE *f)
  241. {
  242.     int c, n = 79;
  243.     char *p = buf;
  244.  
  245.     do {
  246.         c = getc(f);
  247.         if (c == '\n' || c == '\r' || c == EOF)
  248.             break;
  249.         *p++ = c;
  250.     } while (--n > 0);
  251.     if (p == buf && c == EOF)
  252.     {    *buf = '\0';
  253.         return NULL;
  254.     }
  255.     /* skip to end of line */
  256.     while (c != '\n' && c != '\r' && c != EOF)
  257.         c = getc(f);
  258.     if (c == '\r' && (c = getc(f)) != '\n')
  259.         ungetc(c, f);
  260.     while (--p >= buf && *p == ' ')
  261.         ;
  262.     *++p = '\0';
  263.     return buf;
  264. }
  265.  
  266.  
  267. /*    Encode a file in sections.  64 ASCII bytes * 720 lines = 46K, 
  268.     recommended max.  Usenet message size is 50K so this leaves a nice 
  269.     margin for .signature.  In the interests of orthogonality and 
  270.     programmer laziness no check is made for a message containing only 
  271.     a few lines (or even just an 'end')    after a section break. 
  272. */
  273. #define LINE_LEN    48L
  274. int pem_lines = 720;
  275. #define BYTES_PER_SECTION    (LINE_LEN * pem_lines)
  276.  
  277. #ifdef MSDOS    /* limited stack space */
  278. #define MAX_LINE_SIZE    256
  279. #else
  280. #define MAX_LINE_SIZE    1024
  281. #endif
  282.  
  283. #ifndef VMS
  284. /* armored files are opened in binary mode so that CRLF/LF/CR files
  285.    can be handled by all systems */
  286. #define    FOPRPEM    FOPRBIN
  287. #else
  288. #define    FOPRPEM    FOPRTXT
  289. #endif
  290.  
  291. extern boolean verbose;    /* Undocumented command mode in PGP.C */
  292. extern boolean filter_mode;
  293.  
  294. /*
  295.  * Copy from infilename to outfilename, PEM encoding as you go along,
  296.  * and with breaks every
  297.  * pem_lines lines.
  298.  * If clearfilename is non-NULL, first output that file preceded by a
  299.  * special header line.
  300.  */
  301. static
  302. int pem_file(char *infilename, char *outfilename, char *clearfilename)
  303. {
  304.     char buffer[MAX_LINE_SIZE];
  305.     int i,rc,bytesRead,lines = 0;
  306.     int noSections, currentSection = 1;
  307.     long fileLen;
  308.     crcword crc;
  309.     FILE *inFile, *outFile, *clearFile;
  310.     char *blocktype = "MESSAGE";
  311.  
  312.     /* open input file as binary */
  313.     if ((inFile = fopen(infilename,FOPRBIN)) == NULL)
  314.     {   
  315.         return(1);
  316.     }
  317.  
  318.     if (!outfilename || pem_lines == 0)
  319.         noSections = 1;
  320.     else
  321.     {    /* Evaluate how many parts this file will comprise */
  322.         fseek(inFile,0L,SEEK_END);
  323.         fileLen = ftell(inFile);
  324.         rewind(inFile);
  325.         noSections = (fileLen + BYTES_PER_SECTION - 1) / BYTES_PER_SECTION;
  326.         if (noSections > 99)
  327.         {
  328.             pem_lines = ((fileLen+LINE_LEN-1)/LINE_LEN + 98) / 99;
  329.             noSections = (fileLen + BYTES_PER_SECTION - 1) / BYTES_PER_SECTION;
  330.             fprintf(pgpout, "value for \"armorlines\" is too low, using %d\n", pem_lines);
  331.         }
  332.     }
  333.     
  334.     if (outfilename == NULL)
  335.         outFile = stdout;
  336.     else
  337.     {    if (noSections > 1)
  338.         {    force_extension(outfilename, ASC_EXTENSION);
  339.             outFile = fopen (numFilename (outfilename, 1), FOPWTXT);
  340.         }
  341.         else
  342.             outFile = fopen(outfilename,FOPWTXT);
  343.     }
  344.  
  345.     if (outFile == NULL)
  346.     {    fclose(inFile);
  347.         return(1);
  348.     }
  349.  
  350.     if (clearfilename)
  351.     {    if ((clearFile = fopen(clearfilename,FOPRTXT)) == NULL)
  352.         {    fclose (inFile);
  353.             if (outFile != stdout)
  354.                 fclose (outFile);
  355.             return(1);
  356.         }
  357.         fprintf (outFile, "-----BEGIN PGP SIGNED MESSAGE-----\n\n");
  358.         while (fgets(buffer, sizeof(buffer), clearFile) != NULL)
  359.         {
  360.             /* Quote lines beginning with '-' as per RFC1113;
  361.              * Also quote lines beginning with "From ";
  362.              * this is for Unix systems which add ">" to such lines.
  363.              */
  364.             if (buffer[0] == '-' || (strncmp(buffer, "From ", 5)==0))
  365.                 fputs("- ", outFile);
  366.             fputs(buffer, outFile);
  367.         }
  368.         fclose (clearFile);
  369.         putc('\n', outFile);
  370.         blocktype = "SIGNATURE";
  371.     }
  372.  
  373.  
  374.     if (noSections == 1)
  375.     {
  376.         byte ctb = 0;
  377.         ctb = getc(inFile);
  378.         if (is_ctb_type(ctb, CTB_CERT_PUBKEY_TYPE))
  379.             blocktype = "PUBLIC KEY BLOCK";
  380.         fprintf (outFile, "-----BEGIN PGP %s-----\n",blocktype);
  381.         rewind(inFile);
  382.     }
  383.     else
  384.         fprintf (outFile, "-----BEGIN PGP MESSAGE, PART %02d/%02d-----\n",
  385.                     1, noSections);
  386.     fprintf (outFile, "Version: %s\n",rel_version);
  387.     fprintf (outFile, "\n");
  388.  
  389.     init_crc();
  390.     crc = CRCINIT;
  391.  
  392.     while((bytesRead = fread(buffer,1,LINE_LEN,inFile)) > 0)
  393.     {    /* Munge up LINE_LEN characters */
  394.         if (bytesRead < LINE_LEN)
  395.             fill0 (buffer+bytesRead, LINE_LEN-bytesRead);
  396.  
  397.         for (i=0; i<bytesRead-2; i+=3) {
  398.             crc = crcupdate(buffer[i],crc);
  399.             crc = crcupdate(buffer[i+1],crc);
  400.             crc = crcupdate(buffer[i+2],crc);
  401.             outdec(buffer+i,outFile,3);
  402.         }
  403.  
  404.         if (i<bytesRead) {
  405.             outdec(buffer+i,outFile,bytesRead-i);
  406.             while (i<bytesRead)
  407.                 crc = crcupdate(buffer[i++],crc);
  408.         }
  409.         putc('\n',outFile);
  410.  
  411.         if (++lines == pem_lines && currentSection < noSections)
  412.         {    lines = 0;
  413.             outcrc (crc, outFile);
  414.             fprintf(outFile,"-----END PGP MESSAGE, PART %02d/%02d-----\n\n",
  415.                 currentSection, noSections);
  416.             if (write_error(outFile))
  417.             {    fclose(outFile);
  418.                 return(-1);
  419.             }
  420.             fclose (outFile);
  421.             outFile = fopen (numFilename (outfilename, ++currentSection), FOPWTXT);
  422.             if (outFile == NULL)
  423.             {    fclose(inFile);
  424.                 return(-1);
  425.             }
  426.             fprintf(outFile,"-----BEGIN PGP MESSAGE, PART %02d/%02d-----\n",
  427.                     currentSection, noSections);
  428.             fprintf(outFile,"\n");
  429.             crc = CRCINIT;
  430.         }
  431.     }
  432.     outcrc (crc, outFile);
  433.  
  434.     if (noSections == 1)
  435.         fprintf (outFile, "-----END PGP %s-----\n",blocktype);
  436.     else
  437.         fprintf(outFile,"-----END PGP MESSAGE, PART %02d/%02d-----\n",
  438.                 noSections, noSections);
  439.  
  440.     /* Done */
  441.     fclose(inFile);
  442.     rc = write_error(outFile);
  443.     if (outFile == stdout)
  444.         return rc;
  445.     fclose(outFile);
  446.  
  447.     if (rc)
  448.         return(-1);
  449.  
  450.     if (clearfilename)
  451.         fprintf (pgpout, PSTR("\nClear signature file: %s\n"), outfilename);
  452.     else if (noSections == 1)
  453.         fprintf (pgpout, PSTR("\nTransport armor file: %s\n"), outfilename);
  454.     else
  455.     {
  456.         fprintf (pgpout, PSTR("\nTransport armor files: "));
  457.         for (i=1; i<=noSections; ++i)
  458.             fprintf (pgpout, "%s%s", numFilename(outfilename,i),
  459.                         i==noSections?"\n":", ");
  460.     }
  461.     return(0);
  462. }    /* pem_file */
  463.  
  464. /*     End PEM encode routines. */
  465.  
  466.  
  467. /*    PEM decode routines.
  468. */
  469.  
  470. static
  471. int dpem_buffer(char *inbuf, char *outbuf, int *outlength)
  472. {
  473.     unsigned char *bp;
  474.     int    length;
  475.     unsigned int c1,c2,c3,c4;
  476.     register int j;
  477.  
  478.     length = 0;
  479.     bp = (unsigned char *)inbuf;
  480.  
  481.     /* FOUR input characters go into each THREE output charcters */
  482.  
  483.     while (*bp!='\0')
  484.     {    if (*bp&0x80 || (c1=asctobin[*bp])&0x80)
  485.             return -1;
  486.         ++bp;
  487.         if (*bp&0x80 || (c2=asctobin[*bp])&0x80)
  488.             return -1;
  489.         if (*++bp == PAD)
  490.         {    c3 = c4 = 0;
  491.             length += 1;
  492.             if (c2 & 15)
  493.                 return -1;
  494.             if (strcmp((char *)bp, "==") == 0)
  495.                 bp += 1;
  496.             else if (strcmp((char *)bp, "=3D=3D") == 0)
  497.                 bp += 5;
  498.             else
  499.                 return -1;
  500.         }
  501.         else if (*bp&0x80 || (c3=asctobin[*bp])&0x80)
  502.                 return -1;
  503.         else
  504.         {    if (*++bp == PAD)
  505.             {    c4 = 0;
  506.                 length += 2;
  507.                 if (c3 & 3)
  508.                     return -1;
  509.                 if (strcmp((char *)bp, "=") == 0)
  510.                     ; /* All is well */
  511.                 else if (strcmp((char *)bp, "=3D") == 0)
  512.                     bp += 2;
  513.                 else
  514.                     return -1;
  515.             }
  516.             else if (*bp&0x80 || (c4=asctobin[*bp])&0x80)
  517.                 return -1;
  518.             else
  519.                 length += 3;
  520.         }
  521.         ++bp;
  522.         j = (c1 << 2) | (c2 >> 4);
  523.         *outbuf++=j;
  524.         j = (c2 << 4) | (c3 >> 2);
  525.         *outbuf++=j;
  526.         j = (c3 << 6) | c4;
  527.         *outbuf++=j;
  528.     }
  529.  
  530.     *outlength = length;
  531.     return(0);    /* normal return */
  532.  
  533. }    /* dpem_buffer */
  534.  
  535. static char pemfilename[MAX_PATH];
  536. /*
  537.  * try to open the next file of a multi-part armored file
  538.  * the sequence number is expected at the end of the file name
  539.  */
  540. static FILE *
  541. open_next(void)
  542. {
  543.     char *p, *s, c;
  544.     FILE *fp;
  545.  
  546.     p = pemfilename + strlen(pemfilename);
  547.     while (--p >= pemfilename && isdigit(*p))
  548.     {
  549.         if (*p != '9')
  550.         {
  551.             ++*p;
  552.             return(fopen(pemfilename, FOPRPEM));
  553.         }
  554.         *p = '0';
  555.     }
  556.  
  557.     /* need an extra digit */
  558.     if (p >= pemfilename)
  559.     {    /* try replacing character ( .as0 -> .a10 ) */
  560.         c = *p;
  561.         *p = '1';
  562.         if ((fp = fopen(pemfilename, FOPRPEM)) != NULL)
  563.             return(fp);
  564.         *p = c;    /* restore original character */
  565.     }
  566.     ++p;
  567.     for (s = p + strlen(p); s >= p; --s)
  568.         s[1] = *s;
  569.     *p = '1'; /* insert digit ( fn0 -> fn10 ) */
  570.  
  571.     return(fopen(pemfilename, FOPRPEM));
  572. }
  573.  
  574. /*
  575.  * Copy from in to out, decoding as you go, with handling for multiple
  576.  * 500-line blocks of encoded data.
  577.  */
  578. static
  579. int pemdecode(FILE *in, FILE *out)
  580. {
  581. char inbuf[80];
  582. char outbuf[80];
  583.  
  584. int i, n, status;
  585. int line;
  586. int section, currentSection = 1;
  587. int noSections = 0;
  588. int gotcrc = 0;
  589. long crc=CRCINIT, chkcrc = -1;
  590. char crcbuf[4];
  591. int ret_code = 0;
  592. int end_of_message;
  593.  
  594.     init_crc();
  595.  
  596.     for (line = 1; ; line++)    /* for each input line */
  597.     {
  598.         if (get_armor_line(inbuf, in) == NULL)
  599.             end_of_message = 1;
  600.         else
  601.         {    end_of_message = (strncmp(inbuf,"-----END PGP MESSAGE,", 21) == 0);
  602.             ++infile_line;
  603.         }
  604.  
  605.         if (currentSection!=noSections && end_of_message)
  606.         {    /* End of this section */
  607.             if (gotcrc)
  608.             {    if (chkcrc != crc)
  609.                 {    fprintf(pgpout,PSTR("ERROR: Bad ASCII armor checksum in section %d.\n"), currentSection);
  610.                     ret_code = -1;    /* continue with decoding to see if there are other bad parts */
  611.                 }
  612.             }
  613.             gotcrc = 0;
  614.             crc = CRCINIT;
  615.             section = 0;
  616.  
  617.             /* Try and find start of next section */
  618.             do
  619.             {    if (get_armor_line(inbuf,in) == NULL)
  620.                 {    FILE *nextf;
  621.                     if ((nextf = open_next()) != NULL)
  622.                     {
  623.                         fclose(in);
  624.                         in = nextf;
  625.                         continue;
  626.                     }
  627.                     fprintf(pgpout,PSTR("Can't find section %d.\n"),currentSection + 1);
  628.                     return(-1);
  629.                 }
  630.                 ++infile_line;
  631.             }
  632.             while (strncmp(inbuf,"-----BEGIN PGP MESSAGE",22));
  633.  
  634.             /* Make sure this section is the correct one */
  635.             if (2 != sscanf(inbuf,"-----BEGIN PGP MESSAGE, PART %d/%d",
  636.                 §ion,&noSections))
  637.             {    fprintf(pgpout,PSTR("Badly formed section header, part %d.\n"),
  638.                     currentSection+1);
  639.                 return(-1);
  640.             }
  641.             if (section != ++currentSection)
  642.             {    fprintf(pgpout,PSTR("Sections out of order, expected part %d"),currentSection);
  643.                 if (section)
  644.                     fprintf(pgpout,PSTR(", got part %d\n"),section);
  645.                 else
  646.                     fputc('\n',pgpout);
  647.                 return(-1);
  648.             }
  649.  
  650.             /* Skip header after BEGIN line */
  651.             do {
  652.                 ++infile_line;
  653.                 if (get_armor_line(inbuf, in) == NULL)
  654.                 {
  655.                     fprintf(pgpout,PSTR("ERROR: Hit EOF in header of section %d.\n"),
  656.                         currentSection);
  657.                     return(-1);
  658.                 }
  659.             } while (inbuf[0] != '\0');
  660.  
  661.             /* Continue decoding */
  662.             continue;
  663.         }
  664.  
  665.         /* Quit when hit the -----END PGP MESSAGE----- line or a blank,
  666.             or handle checksum */
  667.         if (inbuf[0] == PAD)    /* Checksum lines start with PAD char */
  668.         {
  669.             /* If the already-armored file is sent through MIME
  670.              * and gets armored again, '=' will become '=3D'.
  671.              * To make life easier, we detect and work around this
  672.              * idiosyncracy.
  673.              */
  674.             if (strlen(inbuf) == 7 &&
  675.                 inbuf[1] == '3' && inbuf[2] == 'D')
  676.                 status = dpem_buffer(inbuf+3, crcbuf, &n);
  677.             else
  678.                 status = dpem_buffer(inbuf+1, crcbuf, &n);
  679.             if ( status < 0 || n != 3 )
  680.             {    fprintf(pgpout,PSTR("ERROR: Badly formed ASCII armor checksum, line %d.\n"),line);
  681.                 return -1;
  682.             }
  683.             chkcrc = (((long)crcbuf[0]<<16)&0xff0000L) +
  684.                 ((crcbuf[1]<<8)&0xff00L) + (crcbuf[2]&0xffL);
  685.             gotcrc = 1;
  686.             continue;
  687.         }
  688.         if (inbuf[0] == '\0')
  689.         {    fprintf(pgpout,PSTR("WARNING: No ASCII armor `END' line.\n"));
  690.             break;
  691.         }
  692.         if (strncmp(inbuf, "-----END PGP ", 13) == 0)
  693.             break;
  694.  
  695.         status = dpem_buffer(inbuf,outbuf,&n);
  696.  
  697.         if (status == -1)
  698.         {    fprintf(pgpout,PSTR("ERROR: Bad ASCII armor character, line %d.\n"), line);
  699.             gotcrc = 1;    /* this will print part number, continue with next part */
  700.             ret_code = -1;
  701.         }
  702.  
  703.         if (n > sizeof outbuf)
  704.         {    fprintf(pgpout,PSTR("ERROR: Bad ASCII armor line length %d on line %d.\n"),
  705.                     n, line);
  706.             return -1;
  707.         }
  708.  
  709.         for (i=0; i<n; ++i)
  710.             crc = crcupdate(outbuf[i],crc);
  711.         if (fwrite(outbuf,1,n,out) != n)
  712.         {    ret_code = -1;
  713.             break;
  714.         }
  715.  
  716.     }    /* line */
  717.  
  718.     if (gotcrc)
  719.     {    if (chkcrc != crc)
  720.         {    fprintf(pgpout,PSTR("ERROR: Bad ASCII armor checksum"));
  721.             if (noSections > 0)
  722.                 fprintf(pgpout,PSTR(" in section %d"), noSections);
  723.             fputc('\n',pgpout);
  724.             return -1;
  725.         }
  726.     }
  727.     else
  728.         fprintf(pgpout,PSTR("Warning: Transport armor lacks a checksum.\n"));
  729.  
  730.     return(ret_code);    /* normal return */
  731. }   /* pemdecode */
  732.  
  733.  
  734. static
  735. boolean is_pemfile(char *infile)
  736. {
  737.     FILE    *in;
  738.     char    inbuf[80];
  739.     char    outbuf[80];
  740.     int     n, status;
  741.     long    il;
  742.  
  743.     if ((in = fopen(infile, FOPRPEM)) == NULL)
  744.     {    /* can't open file */
  745.         return(FALSE);
  746.     }
  747.  
  748.     /* Read to infile_line before we begin looking */
  749.     for (il=0; il<infile_line; ++il)
  750.     {
  751.         if (get_armor_line(inbuf, in) == NULL)
  752.         {    fclose(in);
  753.             return(FALSE);
  754.         }
  755.     }
  756.  
  757.     /* search file for header line */
  758.     for (;;)
  759.     {
  760.         if (get_armor_line(inbuf, in) == NULL)
  761.             break;
  762.         else
  763.         {
  764.             if (strncmp(inbuf, "-----BEGIN PGP ", 15) == 0)
  765.             {
  766.                 if (strncmp(inbuf,"-----BEGIN PGP SIGNED MESSAGE-----",34)==0) {
  767.                     fclose(in);
  768.                     return(TRUE);
  769.                 }
  770.                 do {
  771.                     if (get_armor_line(inbuf, in) == NULL)
  772.                         break;
  773. #ifndef STRICT_PEM
  774.                     if (dpem_buffer(inbuf,outbuf,&n) == 0 && n == 48)
  775.                     {    fclose(in);
  776.                         return(TRUE);
  777.                     }
  778. #endif
  779.                 } while (inbuf[0] != '\0');
  780.                 if (get_armor_line(inbuf, in) == NULL)
  781.                     break;
  782.                 status = dpem_buffer(inbuf,outbuf,&n);
  783.                 if (status < 0)
  784.                     break;
  785.                 fclose(in);
  786.                 return(TRUE);
  787.             }
  788.         }
  789.     }
  790.  
  791.     fclose(in);
  792.     return(FALSE);
  793.  
  794. }    /* is_pemfile */
  795.  
  796.  
  797. static
  798. int dpem_file(char *infile, char *outfile)
  799. {
  800. FILE    *in, *out;
  801. char    buf[MAX_LINE_SIZE];
  802. char    outbuf[80];
  803. int        status, n;
  804. long    il, fpos;
  805. char    *litfile = NULL;
  806.  
  807.     if ((in = fopen(infile, FOPRPEM)) == NULL)
  808.     {
  809.         fprintf(pgpout,PSTR("ERROR: Can't find file %s\n"), infile);
  810.         return(10);
  811.     }
  812.     strcpy(pemfilename, infile);    /* store filename for multi-parts */
  813.  
  814.     /* Skip to infile_line */
  815.     for (il=0; il<infile_line; ++il)
  816.     {
  817.         if (get_armor_line(buf, in) == NULL)
  818.         {    fclose(in);
  819.             return -1;
  820.         }
  821.     }
  822.  
  823.     /* Loop through file, searching for header.  Decode anything with a
  824.        header, complain if there were no headers. */
  825.  
  826.     /* search file for header line */
  827.     for (;;)
  828.     {
  829.         ++infile_line;
  830.         if (get_armor_line(buf, in) == NULL)
  831.         {
  832.             fprintf(pgpout,PSTR("ERROR: No ASCII armor `BEGIN' line!\n"));
  833.             fclose(in);
  834.             return(12);
  835.         }
  836.         if (strncmp(buf, "-----BEGIN PGP ", 15) == 0)
  837.             break;
  838.     }
  839.     if (strncmp(buf, "-----BEGIN PGP SIGNED MESSAGE-----", 34) == 0) {
  840.         FILE    *litout;
  841.         char    *canonfile, *p;
  842.         boolean    inheader = TRUE;
  843.         boolean    nline = FALSE;
  844.  
  845.         litfile = tempfile(TMP_WIPE|TMP_TMPDIR);
  846.         if ((litout = fopen (litfile, FOPWTXT)) == NULL)
  847.         {    fprintf(pgpout,PSTR("\n\007Unable to write ciphertext output file '%s'.\n"), litfile);
  848.             fclose(in);
  849.             return(-1);
  850.         }
  851.         for ( ; ; )
  852.         {    ++infile_line;
  853.             if (fgets(buf, sizeof buf, in) == NULL)
  854.             {    fprintf(pgpout,PSTR("ERROR: ASCII armor decode input ended unexpectedly!\n"));
  855.                 fclose(in);
  856.                 fclose(litout);
  857.                 rmtemp (litfile);
  858.                 return(12);
  859.             }
  860.             /* skip header lines including blank separator line */
  861.             if (inheader)
  862.             {    for (p=buf; *p==' ' || *p == '\r'; ++p)
  863.                     ;
  864.                 if (*p == '\n')
  865.                     inheader = FALSE;
  866.             }
  867.             else
  868.             {    if (strncmp(buf,"-----BEGIN PGP ", 15) == 0)
  869.                     break;
  870.                 if (nline)
  871.                     putc('\n', litout);
  872.                 p = buf + strlen(buf) - 1;
  873.                 if (p >= buf && *p == '\n')
  874.                 {    nline = TRUE;
  875.                 /* remove \n, original file may have ended in unterminated line */
  876.                     *p = '\0';
  877.                 }
  878.                 /* De-quote lines starting with '- ' */
  879.                 fputs(buf + ((buf[0]=='-'&&buf[1]==' ')?2:0), litout);
  880.             }
  881.         }
  882.         fflush (litout);
  883.         if (ferror(litout))
  884.         {    fclose(litout);
  885.             fclose(in);
  886.             rmtemp (litfile);
  887.             return(-1);
  888.         }
  889.         fclose (litout);
  890.         canonfile = tempfile(TMP_WIPE|TMP_TMPDIR);
  891.         strip_spaces = TRUE;
  892.         make_canonical (litfile, canonfile);
  893.         rmtemp (litfile);
  894.         litfile = canonfile;
  895.     }
  896.  
  897.     /* Skip header after BEGIN line */
  898.     do {
  899.         ++infile_line;
  900.         fpos = ftell(in);
  901.         if (get_armor_line(buf, in) == NULL)
  902.         {
  903.             fprintf(pgpout,PSTR("ERROR: Hit EOF in header.\n"));
  904.             fclose(in);
  905.             return(13);
  906.         }
  907. #ifndef STRICT_PEM
  908.         if (dpem_buffer(buf,outbuf,&n) == 0 && n == 48)
  909.         {    fseek(in, fpos, SEEK_SET);
  910.             --infile_line;
  911.             break;
  912.         }
  913. #endif
  914.     } while (buf[0] != '\0');
  915.  
  916.     if ((out = fopen(outfile, FOPWBIN)) == NULL)
  917.     {    fprintf(pgpout,PSTR("\n\007Unable to write ciphertext output file '%s'.\n"), outfile);
  918.         fclose(in);
  919.         return(-1);
  920.     }
  921.  
  922.     status = pemdecode(in, out);
  923.  
  924.     if (litfile)
  925.     {    /* Glue the literal file read above to the signature */
  926.         char lit_mode=MODE_TEXT;    
  927.         word32 dummystamp = 0;
  928.         FILE *f = fopen(litfile,FOPRBIN);
  929.         write_ctb_len (out, CTB_LITERAL2_TYPE, fsize(f)+6, FALSE);
  930.         fwrite ( &lit_mode, 1, 1, out );    /*    write lit_mode */
  931.         fputc ('\0', out);            /* No filename */
  932.         fwrite ( &dummystamp, 1, sizeof(dummystamp), out); /* dummy timestamp */
  933.         copyfile(f,out,-1L);        /* Append literal file */
  934.         fclose (f);
  935.         rmtemp(litfile);
  936.     }
  937.  
  938.     if (write_error(out))
  939.         status = -1;
  940.     fclose(out);
  941.     fclose(in);
  942.     return(status);
  943. }   /* dpem_file */
  944.  
  945. /* Entry points for generic interface names */
  946. int
  947. armor_file (char *infile, char *outfile, char *filename, char *clearname)
  948. {
  949.     if (verbose)
  950.         fprintf(pgpout,"armor_file: infile = %s, outfile = %s, filename = %s, clearname = %s\n",
  951.             infile, outfile, filename, clearname);
  952.     return pem_file (infile, outfile, clearname);
  953. }
  954.  
  955. int
  956. de_armor_file(char *infile, char *outfile, long *curline)
  957. {
  958.     int status;
  959.  
  960.     if (verbose)
  961.         fprintf(pgpout,"de_armor_file: infile = %s, outfile = %s, curline = %ld\n",
  962.             infile, outfile, *curline);
  963.     infile_line = (curline ? *curline : 0);
  964.     status = dpem_file (infile, outfile);
  965.     if (curline)
  966.         *curline = infile_line;
  967.     return status;
  968. }
  969.  
  970. boolean
  971. is_armor_file (char *infile, long startline)
  972. {
  973.     infile_line = startline;
  974.     return is_pemfile (infile);
  975. }
  976.